<?php


namespace App\Console\Commands\Channel;


use Illuminate\Console\Command;

class UserDataCommand extends Command
{
    //命令名
    protected $signature = 'channel:user-data';

    //命令描述
    protected $description = '渠道用户数据统计';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //查询所有渠道分期
        $channelStages = app('model_channel_stage')->select('id', 'channel_id')->get();

        foreach ($channelStages as $channelStage) {

            //查询渠道分期下的用户
            $users = app('model_user')
                ->select('user_id')
                ->where('channel_stage_id', $channelStage->id)
                ->get();

            foreach ($users as $user) {
                //统计充值金额
                $rechargeTotal = app('model_user_recharge')
                    ->where('user_id', $user->user_id)
                    ->where('status', 2)
                    ->sum('money');
                //统计收益
                $earningsTotal = app('model_give_gift_charm')
                    ->where('user_id', $user->user_id)
                    ->sum('total');
                //统计观看直播的时长
                $watchLiveDuration = app('repo_statistics')->watchLiveDuration($user->user_id);

                $data = [
                    'recharge_total' => $rechargeTotal,
                    'earnings_total' => $earningsTotal,
                    'watch_live_duration' => $watchLiveDuration,
                ];

                //新增或更新统计数据
                $channelUserData = app('model_channel_user_data')->select('user_id')->where('user_id', $user->user_id)->first();
                if ($channelUserData) {
                    app('model_channel_user_data')->where('user_id', $user->user_id)->update($data);
                } else {
                    $data['user_id'] = $user->user_id;
                    $data['channel_id'] = $channelStage->channel_id;
                    $data['channel_stage_id'] = $channelStage->id;
                    app('model_channel_user_data')->insert($data);
                }
            }
        }
    }
}